<template>
  <div class="question-bank">
    <a-tabs v-model:activeKey="activeTab">
      <a-tab-pane key="question-list" tab="题目列表" />
      <a-tab-pane key="upload-question" tab="上传题目" />
      <a-tab-pane key="tag-management" tab="知识点标签管理" />
    </a-tabs>

    <!-- 题目列表 -->
    <div v-show="activeTab === 'question-list'" class="tab-content question-list-tab">
      <a-card>
        <div class="filter-section">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-select v-model:value="filter.questionType" placeholder="题目类型" style="width: 100%">
                <a-select-option value="single-choice">单选题</a-select-option>
                <a-select-option value="multiple-choice">多选题</a-select-option>
                <a-select-option value="fill-blank">填空题</a-select-option>
                <a-select-option value="true-false">判断题</a-select-option>
              </a-select>
            </a-col>
          </a-row>
        </div>

        <a-table 
          :columns="questionColumns" 
          :data-source="questionData" 
          :pagination="{ pageSize: 10 }"
          style="margin-top: 20px;"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'tags'">
              <a-tag v-for="tag in record.tags" :key="tag" color="blue">{{ tag }}</a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="editQuestion(record.id)">编辑</a-button>
              <a-button type="link" danger @click="deleteQuestion(record.id)">删除</a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 上传题目 -->
    <div v-show="activeTab === 'upload-question'" class="tab-content upload-question-tab">
      <a-card>
        <a-tabs v-model:activeKey="uploadMethod">
          <a-tab-pane key="manual" tab="手动输入" force-render>
            <a-form :model="manualQuestionForm" layout="vertical">
              <a-form-item label="题目类型">
                <a-select v-model:value="manualQuestionForm.type" placeholder="请选择题目类型" style="width: 300px;">
                  <a-select-option value="single-choice">单选题</a-select-option>
                  <a-select-option value="multiple-choice">多选题</a-select-option>
                  <a-select-option value="fill-blank">填空题</a-select-option>
                  <a-select-option value="true-false">判断题</a-select-option>
                  <a-select-option value="short-answer">简答题</a-select-option>
                </a-select>
              </a-form-item>
              
              <a-form-item label="题目内容">
                <a-textarea 
                  v-model:value="manualQuestionForm.content" 
                  placeholder="请输入题目内容" 
                  :rows="4" 
                />
              </a-form-item>
              
              <!-- 选择题选项 -->
              <div v-if="manualQuestionForm.type === 'single-choice' || manualQuestionForm.type === 'multiple-choice'">
                <a-form-item label="选项">
                  <a-row v-for="(option, index) in manualQuestionForm.options" :key="index" :gutter="8" style="margin-bottom: 10px;">
                    <a-col :span="2">
                      <span>{{ String.fromCharCode(65 + index) }}.</span>
                    </a-col>
                    <a-col :span="18">
                      <a-input v-model:value="option.text" placeholder="选项内容" />
                    </a-col>
                    <a-col :span="4">
                      <a-checkbox v-if="manualQuestionForm.type === 'multiple-choice'" v-model:checked="option.correct">正确答案</a-checkbox>
                      <a-radio 
                        v-if="manualQuestionForm.type === 'single-choice'" 
                        :checked="option.correct" 
                        @change="setSingleCorrect(index)"
                      >
                        正确答案
                      </a-radio>
                    </a-col>
                  </a-row>
                  <a-button type="dashed" @click="addOption" style="width: 100%; margin-top: 10px;">
                    <PlusOutlined /> 添加选项
                  </a-button>
                </a-form-item>
              </div>
              
              <!-- 判断题答案 -->
              <div v-if="manualQuestionForm.type === 'true-false'">
                <a-form-item label="正确答案">
                  <a-radio-group v-model:value="manualQuestionForm.trueFalseAnswer">
                    <a-radio :value="true">正确</a-radio>
                    <a-radio :value="false">错误</a-radio>
                  </a-radio-group>
                </a-form-item>
              </div>
              <div v-if="manualQuestionForm.type === 'fill-blank'">
                <a-form-item label="填空答案">
                  <a-row v-for="(answer, index) in manualQuestionForm.fillAnswers" :key="index" :gutter="8" style="margin-bottom: 10px;">
                    <a-col :span="4">
                      <span>第{{ index + 1 }}空：</span>
                    </a-col>
                    <a-col :span="16">
                      <a-input v-model:value="answer.text" placeholder="请输入该空的答案" />
                    </a-col>
                    <a-col :span="4">
                      <a-button 
                        v-if="manualQuestionForm.fillAnswers.length > 1" 
                        type="link" 
                        danger 
                        @click="removeFillAnswer(index)"
                      >
                        删除
                      </a-button>
                    </a-col>
                  </a-row>
                  <a-button type="dashed" @click="addFillAnswer" style="width: 100%; margin-top: 10px;">
                    <PlusOutlined /> 添加填空
                  </a-button>
                </a-form-item>
              </div>
              
              <!-- 答案解析 -->
              <a-form-item label="答案解析">
                <a-textarea 
                  v-model:value="manualQuestionForm.explanation" 
                  placeholder="请输入答案解析" 
                  :rows="3" 
                />
                <a-button 
                  style="margin-top: 10px;" 
                  @click="generateExplanationByAI"
                  :loading="aiGeneratingExplanation"
                >
                  AI生成
                </a-button>
              </a-form-item>
              
              <a-form-item label="分类标签">
  <a-select 
    v-model:value="manualQuestionForm.tagCategory" 
    placeholder="请选择分类标签" 
    style="width: 100%"
    @change="manualQuestionForm.tagIds = []"
  >
    <a-select-option v-for="cat in level1Tags" :key="cat" :value="cat">
      {{ cat }}
    </a-select-option>
  </a-select>
</a-form-item>

<a-form-item label="具体标签">
  <a-select 
    v-model:value="manualQuestionForm.tagIds" 
    mode="multiple" 
    :disabled="!manualQuestionForm.tagCategory"
    placeholder="请选择具体标签"
    style="width: 100%"
  >
    <a-select-option 
      v-for="tag in getLevel2Tags(manualQuestionForm.tagCategory)" 
      :key="tag.id" 
      :value="tag.id"
    >
      {{ tag.name }}
    </a-select-option>
  </a-select>
</a-form-item>
              
              <a-form-item>
                <a-button type="primary" @click="submitManualQuestion">提交题目</a-button>
              </a-form-item>
            </a-form>
          </a-tab-pane>
          
          <a-tab-pane key="file" tab="文件上传">
            <a-form :model="fileQuestionForm" layout="vertical">
              <a-form-item label="选择文件">
                <a-upload-dragger
                  :beforeUpload="beforeFileUpload"
                  :fileList="fileList"
                  accept=".doc,.docx,.pdf,.jpg,.jpeg,.png"
                >
                  <p class="ant-upload-drag-icon">
                    <inbox-outlined />
                  </p>
                  <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
                  <p class="ant-upload-hint">
                    支持Word、PDF、图片格式文件
                  </p>
                </a-upload-dragger>
              </a-form-item>
              
              <a-form-item label="1级标签">
  <a-select 
    v-model:value="fileQuestionForm.tagCategory" 
    placeholder="请选择1级标签" 
    style="width: 100%"
    @change="fileQuestionForm.tagIds = []"
  >
    <a-select-option v-for="cat in level1Tags" :key="cat" :value="cat">
      {{ cat }}
    </a-select-option>
  </a-select>
</a-form-item>

<a-form-item label="2级标签">
  <a-select 
    v-model:value="fileQuestionForm.tagIds" 
    mode="multiple" 
    :disabled="!fileQuestionForm.tagCategory"
    placeholder="请选择2级标签"
    style="width: 100%"
  >
    <a-select-option 
      v-for="tag in getLevel2Tags(fileQuestionForm.tagCategory)" 
      :key="tag.id" 
      :value="tag.id"
    >
      {{ tag.name }}
    </a-select-option>
  </a-select>
</a-form-item>
              
              <a-form-item>
                <a-button 
                  type="primary" 
                  :disabled="fileList.length === 0" 
                  @click="submitFileQuestions"
                >
                  上传并解析
                </a-button>
                <a-button style="margin-left: 10px;" @click="aiParseQuestions" :loading="aiParsing">
                  AI智能解析
                </a-button>
              </a-form-item>
            </a-form>
            
            <!-- AI解析结果展示 -->
            <div v-if="aiParsedQuestions.length > 0" class="ai-parse-result">
              <h3>AI解析结果</h3>
              <a-list
                :data-source="aiParsedQuestions"
                item-layout="vertical"
              >
                <template #renderItem="{ item }">
                  <a-list-item>
                    <a-card>
                      <template #title>
                        <a-checkbox v-model:checked="item.selected"> 选择此题</a-checkbox>
                      </template>
                      <p><strong>题目内容:</strong> {{ item.content }}</p>
                      <p><strong>选项:</strong> {{ item.options ? item.options.join(', ') : '无' }}</p>
                      <p><strong>答案:</strong> {{ item.answer }}</p>
                      <p><strong>解析:</strong> {{ item.explanation }}</p>
                    </a-card>
                  </a-list-item>
                </template>
              </a-list>
              <a-button type="primary" @click="confirmAiParsedQuestions">确认并添加选中题目</a-button>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>

    <!-- 知识点标签管理 -->
    <div v-show="activeTab === 'tag-management'" class="tab-content tag-management-tab">
      <a-card>
        <a-collapse v-model:activeKey="activeTagCategories" accordion>
          <a-collapse-panel 
            v-for="category in level1Tags" 
            :key="category" 
            :header="category"
            @click="onCategoryExpand(category)"
          >
            <div class="tag-panel-content">
              <div class="level2-tags-list">
                <a-tag 
                  v-for="tag in getLevel2Tags(category)" 
                  :key="tag.id"
                  color="blue"
                  class="level2-tag"
                  @click="editLevel2Tag(category, tag)"
                >
                  {{ tag.name }}
                </a-tag>
                <a-tag 
                  class="level2-tag add-tag"
                  @click="showAddTagModal(category)"
                >
                  <PlusOutlined /> 新增标签
                </a-tag>
              </div>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
    </div>

    <!-- 新增/编辑2级标签弹窗 -->
    <a-modal 
      v-model:open="tagModalVisible" 
      :title="isEditingTag ? '编辑2级标签' : '新增2级标签'"
      @ok="handleTagSubmit"
      @cancel="handleTagCancel"
    >
      <a-form :model="tagForm" layout="vertical">
        <a-form-item label="1级标签">
          <a-input v-model:value="tagForm.level1Tag" disabled />
        </a-form-item>
        <a-form-item label="2级标签名称">
          <a-input 
            v-model:value="tagForm.tagName" 
            placeholder="请输入2级标签名称"
          />
        </a-form-item>
      </a-form>
      <template #footer>
        <div style="display: flex; justify-content: space-between;">
          <a-button 
            v-if="isEditingTag" 
            danger 
            @click="handleTagDelete"
          >
            删除标签
          </a-button>
          <div style="margin-left: auto;">
            <a-button @click="handleTagCancel">取消</a-button>
            <a-button type="primary" @click="handleTagSubmit" style="margin-left: 8px;">确定</a-button>
          </div>
        </div>
      </template>
    </a-modal>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined, InboxOutlined } from '@ant-design/icons-vue';
import axios from 'axios';

// 创建axios实例用于题库请求
const request = axios.create({
  baseURL: '/api',
  timeout: 5000
});

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('jwt_token');
    if (token) {
      config.headers.JWTtoken = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// ==================== 全局状态 ====================
const activeTab = ref('question-list');
const uploadMethod = ref('manual');

// ===================================== 题目列表模块 ===============================
// 筛选条件
const filter = reactive({
  questionType: undefined
});

// 题目数据
const questionData = ref([]);

// 表格列配置
const questionColumns = [
  { title: '题目内容', dataIndex: 'content', key: 'content' },
  { title: '类型', dataIndex: 'type', key: 'type' },
  { title: '难度', dataIndex: 'difficulty', key: 'difficulty' },
  { title: '知识点标签', key: 'tags' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
  { title: '操作', key: 'action' }
];

// 编辑题目
const editQuestion = (id) => {
  message.info(`编辑题目 ${id}`);
};

// 删除题目
const deleteQuestion = (id) => {
  message.success(`题目 ${id} 已删除`);
};

// ==================================== 上传题目模块 ==================================
// 手动输入题目表单
const manualQuestionForm = reactive({
  type: 'single-choice',
  content: '',
  options: [
    { text: '', correct: false },
    { text: '', correct: false }
  ],
  fillAnswers: [
    { text: '' },
    { text: '' }
  ],
  trueFalseAnswer: true,
  explanation: '',
  tagCategory: '',
  tagIds: []
});

// 文件上传相关
const fileQuestionForm = reactive({
  tagCategory: '',
  tagIds: []
});
const fileList = ref([]);
const aiParsing = ref(false);
const aiParsedQuestions = ref([]);
const aiGeneratingExplanation = ref(false);

// 设置单选题正确答案
const setSingleCorrect = (index) => {
  manualQuestionForm.options.forEach((option, i) => {
    option.correct = i === index;
  });
};

// 添加选项
const addOption = () => {
  manualQuestionForm.options.push({ text: '', correct: false });
};

// 添加填空答案
const addFillAnswer = () => {
  manualQuestionForm.fillAnswers.push({ text: '' });
};

// 删除填空答案
const removeFillAnswer = (index) => {
  if (manualQuestionForm.fillAnswers.length > 1) {
    manualQuestionForm.fillAnswers.splice(index, 1);
  }
};

// AI生成答案解析
const generateExplanationByAI = async () => {
  if (!manualQuestionForm.content) {
    message.warning('请先输入题目内容');
    return;
  }

  aiGeneratingExplanation.value = true;
  try {
    // 构建AI请求参数
    const requestData = {
      content: manualQuestionForm.content,
      type: manualQuestionForm.type,
      options: [],
      answer: ''
    };

    // 根据题型添加选项和答案信息
    if (manualQuestionForm.type === 'single-choice' || manualQuestionForm.type === 'multiple-choice') {
      requestData.options = manualQuestionForm.options
        .filter(opt => opt.text.trim())
        .map((opt, index) => `${String.fromCharCode(65 + index)}. ${opt.text}`);
      
      if (manualQuestionForm.type === 'single-choice') {
        const correctIndex = manualQuestionForm.options.findIndex(opt => opt.correct);
        if (correctIndex !== -1) {
          requestData.answer = String.fromCharCode(65 + correctIndex);
        }
      } else {
        const correctIndices = manualQuestionForm.options
          .map((opt, idx) => opt.correct ? idx : -1)
          .filter(idx => idx !== -1);
        requestData.answer = correctIndices.map(i => String.fromCharCode(65 + i)).join(', ');
      }
    } else if (manualQuestionForm.type === 'fill-blank') {
      const validAnswers = manualQuestionForm.fillAnswers.filter(ans => ans.text.trim());
      requestData.answer = validAnswers.map(ans => ans.text).join('; ');
    } else if (manualQuestionForm.type === 'true-false') {
      requestData.answer = manualQuestionForm.trueFalseAnswer ? '正确' : '错误';
    }

    console.log('正在请求AI生成答案解析:', requestData);

    // 调用AI接口生成解析
    const response = await request.post('/question/generate-explanation', requestData);
    
    console.log('AI生成解析响应:', response.data);

    if (response.data.code === 1) {
      manualQuestionForm.explanation = response.data.data.explanation || '';
      message.success('AI解析生成成功');
    } else {
      message.error(response.data.msg || 'AI解析生成失败');
    }
  } catch (error) {
    console.error('AI生成解析失败:', error);
    console.error('错误详情:', error.response || error.message);
    message.error(`AI生成解析失败: ${error.message}`);
  } finally {
    aiGeneratingExplanation.value = false;
  }
};

// 提交手动输入的题目
const submitManualQuestion = async () => {
  if (!manualQuestionForm.content) {
    message.warning('请输入题目内容');
    return;
  }

  if (!manualQuestionForm.tagCategory || manualQuestionForm.tagIds.length === 0) {
    message.warning('请选择题目标签');
    return;
  }

  try {
    // 类型映射：将前端类型转换为后端需要的类型
    const typeMapping = {
      'single-choice': 'single',
      'multiple-choice': 'multiple',
      'fill-blank': 'fill',
      'true-false': 'true_false',
      'short-answer': 'short'
    };

    // 构建请求体结构
    const questionData = {
      info: {
        type: typeMapping[manualQuestionForm.type],
        content: manualQuestionForm.content
      },
      detail: {
        analysis: manualQuestionForm.explanation || ''
      },
      tags: []
    };

    // 根据题目类型添加detail字段的特定数据
    if (manualQuestionForm.type === 'single-choice' || manualQuestionForm.type === 'multiple-choice') {
      const validOptions = manualQuestionForm.options.filter(opt => opt.text.trim());
      if (validOptions.length < 2) {
        message.warning('请至少填写两个选项');
        return;
      }

      // 构建optionlist
      questionData.detail.optionlist = validOptions.map((opt, index) => ({
        id: String.fromCharCode(65 + index), // A, B, C, D...
        text: opt.text
      }));

      if (manualQuestionForm.type === 'single-choice') {
        const correctIndex = validOptions.findIndex(opt => opt.correct);
        if (correctIndex === -1) {
          message.warning('请选择一个正确答案');
          return;
        }
        questionData.detail.correctOption = String.fromCharCode(65 + correctIndex);
      } else {
        const correctIndices = validOptions.reduce((acc, opt, index) => {
          if (opt.correct) acc.push(index);
          return acc;
        }, []);
        if (correctIndices.length === 0) {
          message.warning('请至少选择一个正确答案');
          return;
        }
        // 多选题：correctOptionlist为字符串数组，只包含选项ID，如["A", "B"]
        questionData.detail.correctOptionlist = correctIndices.map(i => String.fromCharCode(65 + i));
      }
    } else if (manualQuestionForm.type === 'fill-blank') {
      const validAnswers = manualQuestionForm.fillAnswers.filter(ans => ans.text.trim());
      if (validAnswers.length === 0) {
        message.warning('请填写至少一个答案');
        return;
      }
      // 填空题：answers为数组
      questionData.detail.answers = validAnswers.map(ans => ans.text);
    } else if (manualQuestionForm.type === 'true-false') {
      // 判断题：correctAnswer为Boolean类型，true表示"正确"，false表示"错误"
      questionData.detail.correctAnswer = manualQuestionForm.trueFalseAnswer;
    } else if (manualQuestionForm.type === 'short-answer') {
      // 简答题：可能没有标准答案，或者有参考答案
      // 这里留空或根据实际需求添加
    }

    // 构建tags数组
    const selectedTags = level2TagsData.value[manualQuestionForm.tagCategory] || [];
    questionData.tags = manualQuestionForm.tagIds.map(tagId => {
      const tag = selectedTags.find(t => t.id === tagId);
      return {
        id: tagId,  // 保持为数字类型，不转换为字符串
        category: manualQuestionForm.tagCategory,
        tagName: tag ? tag.name : ''
      };
    });

    console.log('正在提交题目:', questionData);

    const response = await request.post('/questions', questionData);
    console.log('提交题目响应:', response.data);

    if (response.data.code === 1) {
      message.success('题目提交成功');

      // 重置表单
      manualQuestionForm.content = '';
      manualQuestionForm.options = [
        { text: '', correct: false },
        { text: '', correct: false }
      ];
      manualQuestionForm.fillAnswers = [
        { text: '' }
      ];
      manualQuestionForm.trueFalseAnswer = true;
      manualQuestionForm.explanation = '';
      manualQuestionForm.tagCategory = '';
      manualQuestionForm.tagIds = [];

      // 可以在这里刷新题目列表
      // loadQuestionList();
    } else {
      message.error(response.data.msg || '题目提交失败');
    }
  } catch (error) {
    console.error('提交题目失败:', error);
    console.error('错误详情:', error.response || error.message);
    message.error(`提交题目失败: ${error.message}`);
  }
};

// 文件上传前处理
const beforeFileUpload = (file) => {
  const isValidType = file.type === 'application/msword' || 
                     file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                     file.type === 'application/pdf' || 
                     file.type.startsWith('image/');
  
  if (!isValidType) {
    message.error('只能上传Word、PDF或图片文件!');
    return false;
  }
  
  fileList.value = [file];
  return false;
};

// 提交文件题目
const submitFileQuestions = async () => {
  if (fileList.value.length === 0) {
    message.warning('请先选择文件');
    return;
  }

  if (!fileQuestionForm.tagCategory || fileQuestionForm.tagIds.length === 0) {
    message.warning('请选择题目标签');
    return;
  }

  try {
    const file = fileList.value[0];
    const formData = new FormData();
    formData.append('file', file);
    formData.append('tagCategory', fileQuestionForm.tagCategory);
    formData.append('tagIds', JSON.stringify(fileQuestionForm.tagIds));

    console.log('正在上传文件:', {
      fileName: file.name,
      fileSize: file.size,
      fileType: file.type,
      tagCategory: fileQuestionForm.tagCategory,
      tagIds: fileQuestionForm.tagIds
    });

    const response = await request.post('/question/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    console.log('文件上传响应:', response.data);

    if (response.data.code === 1) {
      message.success('文件上传成功，正在解析...');
      fileList.value = [];
      fileQuestionForm.tagCategory = '';
      fileQuestionForm.tagIds = [];
    } else {
      message.error(response.data.msg || '文件上传失败');
    }
  } catch (error) {
    console.error('文件上传失败:', error);
    console.error('错误详情:', error.response || error.message);
    message.error(`文件上传失败: ${error.message}`);
  }
};

// AI解析题目
const aiParseQuestions = async () => {
  if (fileList.value.length === 0) {
    message.warning('请先选择文件');
    return;
  }

  aiParsing.value = true;
  try {
    const file = fileList.value[0];
    const formData = new FormData();
    formData.append('file', file);

    if (fileQuestionForm.tagCategory && fileQuestionForm.tagIds.length > 0) {
      formData.append('tagCategory', fileQuestionForm.tagCategory);
      formData.append('tagIds', JSON.stringify(fileQuestionForm.tagIds));
    }

    console.log('正在AI解析文件:', {
      fileName: file.name,
      fileSize: file.size,
      fileType: file.type,
      tagCategory: fileQuestionForm.tagCategory,
      tagIds: fileQuestionForm.tagIds
    });

    const response = await request.post('/question/ai-parse', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    console.log('AI解析响应:', response.data);

    if (response.data.code === 1) {
      const parsedQuestions = response.data.data.map((q, index) => ({
        id: Date.now() + index,
        selected: true,
        content: q.content,
        options: q.options || [],
        answer: q.answer || '',
        explanation: q.explanation || '',
        tagCategory: fileQuestionForm.tagCategory,
        tagIds: fileQuestionForm.tagIds
      }));

      aiParsedQuestions.value = parsedQuestions;
      message.success(`AI解析成功，识别出 ${parsedQuestions.length} 道题目`);
    } else {
      message.error(response.data.msg || 'AI解析失败');
    }
  } catch (error) {
    console.error('AI解析失败:', error);
    console.error('错误详情:', error.response || error.message);
    message.error(`AI解析失败: ${error.message}`);
  } finally {
    aiParsing.value = false;
  }
};

// 确认AI解析的题目
const confirmAiParsedQuestions = () => {
  const selectedCount = aiParsedQuestions.value.filter(q => q.selected).length;
  message.success(`成功添加 ${selectedCount} 道题目`);
  aiParsedQuestions.value = [];
};

// ========================================= 知识点标签管理模块 =====================================================
// 一级标签列表
const level1Tags = ref([
  "集合论", "逻辑", "关系", "函数", "图论", 
  "树", "组合数学", "代数结构", "布尔代数", "形式语言与自动机"
]);

// 二级标签数据
const level2TagsData = ref({});
const activeTagCategories = ref([]);
const tagModalVisible = ref(false);
const isEditingTag = ref(false);
const tagForm = reactive({
  level1Tag: '',
  tagName: '',
  tagId: null
});

const knowledgeTags = ref([]);

// 知识点标签管理相关方法
// 获取指定1级标签下的所有2级标签
const getLevel2Tags = (category) => {
  return level2TagsData.value[category] || [];
};

// 从后端加载指定1级标签的2级标签数据
const loadLevel2TagsByCategory = async (category) => {
  try {
    console.log(`正在加载${category}的2级标签...`);
    const response = await request.get('/tag', {
      params: { category }
    });
    
    console.log(`${category}的响应数据:`, response.data);
    
    if (response.data.code === 1) {
      // 将返回的数据转换为本地格式
      level2TagsData.value[category] = response.data.data.map(item => ({
        id: item.id,
        name: item.tagName
      }));
      
      console.log(`${category}的2级标签加载成功:`, level2TagsData.value[category]);
      
      // 更新知识点标签列表
      updateKnowledgeTags();
    } else {
      console.warn(`${category}返回code不为1:`, response.data);
      message.warning(`${category}标签数据异常`);
    }
  } catch (error) {
    console.error(`加载${category}的2级标签失败:`, error);
    console.error('错误详情:', error.response || error.message);
    message.error(`加载${category}标签失败: ${error.message}`);
  }
};

// 更新知识点标签列表
const updateKnowledgeTags = () => {
  const tags = [];
  Object.keys(level2TagsData.value).forEach(category => {
    level2TagsData.value[category].forEach(tag => {
      tags.push(tag.name);
    });
  });
  knowledgeTags.value = tags;
};

// 显示新增标签弹窗
const showAddTagModal = (category) => {
  isEditingTag.value = false;
  tagForm.level1Tag = category;
  tagForm.tagName = '';
  tagForm.tagId = null;
  tagModalVisible.value = true;
};

// 编辑2级标签
const editLevel2Tag = (category, tag) => {
  isEditingTag.value = true;
  tagForm.level1Tag = category;
  tagForm.tagName = tag.name;
  tagForm.tagId = tag.id;
  tagModalVisible.value = true;
};

// 提交标签表单
const handleTagSubmit = async () => {
  if (!tagForm.tagName.trim()) {
    message.warning('请输入标签名称');
    return;
  }

  try {
    if (isEditingTag.value) {
      // 编辑标签
      console.log('正在编辑标签:', { id: tagForm.tagId, category: tagForm.level1Tag, tagName: tagForm.tagName });
      
      const response = await request.put('/tag', {
        id: tagForm.tagId,
        category: tagForm.level1Tag,
        tagName: tagForm.tagName
      });
      
      console.log('编辑标签响应:', response.data);
      
      if (response.data.code === 1) {
        message.success('标签修改成功');
        
        // 重新加载该分类的2级标签列表
        await loadLevel2TagsByCategory(tagForm.level1Tag);
      } else {
        message.error(response.data.msg || '修改标签失败');
        return;
      }
    } else {
      // 新增标签
      console.log('正在新增标签:', { category: tagForm.level1Tag, tagName: tagForm.tagName });
      
      const response = await request.post('/tag', {
        category: tagForm.level1Tag,
        tagName: tagForm.tagName
      });
      
      console.log('新增标签响应:', response.data);
      
      if (response.data.code === 1) {
        message.success('标签添加成功');
        
        // 重新加载该分类的2级标签列表
        await loadLevel2TagsByCategory(tagForm.level1Tag);
      } else {
        message.error(response.data.msg || '添加标签失败');
        return;
      }
    }
    
    updateKnowledgeTags();
    tagModalVisible.value = false;
  } catch (error) {
    console.error('保存标签失败:', error);
    console.error('错误详情:', error.response || error.message);
    message.error(`保存标签失败: ${error.message}`);
  }
};

// 取消标签编辑
const handleTagCancel = () => {
  tagModalVisible.value = false;
  tagForm.level1Tag = '';
  tagForm.tagName = '';
  tagForm.tagId = null;
};

// 删除2级标签（从弹窗中调用）
const handleTagDelete = async () => {
  try {
    console.log('正在删除标签:', { id: tagForm.tagId, category: tagForm.level1Tag, name: tagForm.tagName });
    
    // 调用后端API删除标签
    const response = await request.delete('/tag', {
      params: { id: tagForm.tagId }
    });
    
    console.log('删除标签响应:', response.data);
    
    if (response.data.code === 1) {
      message.success('标签删除成功');
      
      // 重新加载该分类的2级标签列表
      await loadLevel2TagsByCategory(tagForm.level1Tag);
      
      updateKnowledgeTags();
      tagModalVisible.value = false;
      
      // 重置表单
      tagForm.level1Tag = '';
      tagForm.tagName = '';
      tagForm.tagId = null;
    } else {
      message.error(response.data.msg || '删除标签失败');
    }
  } catch (error) {
    console.error('删除标签失败:', error);
    console.error('错误详情:', error.response || error.message);
    message.error(`删除标签失败: ${error.message}`);
  }
};

// 当展开某个1级标签时，加载其2级标签
const onCategoryExpand = (category) => {
  // 如果该分类的标签还未加载，则加载
  if (!level2TagsData.value[category] || level2TagsData.value[category].length === 0) {
    loadLevel2TagsByCategory(category);
  }
};

// 组件挂载时预加载全部分类的2级标签
const loadAllLevel2Tags = async () => {
  try {
    console.log('开始预加载所有2级标签...');
    const requests = level1Tags.value.map(category => request.get('/tag', {
      params: { category }
    }));
    const responses = await Promise.all(requests);
    responses.forEach((response, idx) => {
      const category = level1Tags.value[idx];
      if (response.data && response.data.code === 1) {
        level2TagsData.value[category] = response.data.data.map(item => ({
          id: item.id,
          name: item.tagName
        }));
        console.log(`${category}标签加载成功，数量: ${level2TagsData.value[category].length}`);
      } else {
        console.warn(`${category}返回数据异常:`, response.data);
      }
    });
    updateKnowledgeTags();
    console.log('所有2级标签加载完成');
  } catch (error) {
    console.error('加载全部2级标签失败:', error);
    console.error('错误详情:', error.response || error.message);
    message.error(`加载全部标签失败: ${error.message}`);
  }
};

// 页面加载时预加载所有2级标签
onMounted(() => {
  loadAllLevel2Tags();
});

</script>

<style scoped>

.question-bank {
  padding: 20px;
  background-color: #fff;
}

.tab-content {
  margin-top: 20px;
}

.filter-section {
  padding: 20px 0;
  border-bottom: 1px solid #e8e8e8;
}

.ai-parse-result {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.tag-management-tab {
  max-width: 1200px;
}

.tag-panel-content {
  padding: 10px 0;
}

.level2-tags-list {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.level2-tag {
  margin: 8px;
  padding: 8px 16px;
  font-size: 13px;
  cursor: pointer;
  line-height: 1.2;
}

.add-tag {
  border-style: dashed;
}
</style>